package com.saifan.wyy_ov.ui.home;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.BaseActivity;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.ui.communitycenter.CommunitycenterFragment;
import com.saifan.wyy_ov.ui.communitycenter.RoomSelectActivity;
import com.saifan.wyy_ov.ui.communitylife.CommunityLifeFragment;
import com.saifan.wyy_ov.ui.set.Company;
import com.saifan.wyy_ov.ui.set.Project;
import com.saifan.wyy_ov.ui.set.ServerSetActivity;

import com.saifan.wyy_ov.ui.user.LoginActivity;
import com.saifan.wyy_ov.utils.ActivitysManager;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lomasky.ma.httpUtils.HttpUtil;
import lomasky.ma.httpUtils.ICallBack;
import lomasky.ma.httpUtils.JsonUtil;
import lomasky.ma.httpUtils.ResponseBean;
import lomasky.ma.utils.SharedPrefUtil;

public class MainActivity extends BaseActivity {


    BottomNavigationBar bottomNavigationBar;
    ViewPager viewPager;
    boolean isChecked;


    @Override
    protected void onResume() {
        super.onResume();
        if (!isChecked) {
            project = JsonUtil.getObject(SharedPrefUtil.getString(this, "SelectProject", ""), Project.class);

            loadCompanyAndProject();
        }


    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);


        this.bottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        this.viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewBind();


    }

    private void viewBind() {
        viewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager()));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                bottomNavigationBar.selectTab(position);
                mToolbar.setVisibility(position == 2 ? View.GONE : View.VISIBLE);


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        bottomNavigationBar.setActiveColor(R.color.colorPrimaryDark);


        bottomNavigationBar
                .addItem(new BottomNavigationItem(R.mipmap.home_default, "物业云"))
                .addItem(new BottomNavigationItem(R.mipmap.communitylife_default, "社区生活"))
                .addItem(new BottomNavigationItem(R.mipmap.communitycenter_default, "业主中心"))
                .initialise();
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.SimpleOnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                viewPager.setCurrentItem(position);
            }
        });
    }


    //FragmentPagerAdapter
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return HomeFragment.newInstance(position);
                case 1:
                    return CommunityLifeFragment.newInstance(position);
                case 2:
                    return CommunitycenterFragment.newInstance(position);
                default:
                    break;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return null;
        }
    }

    private int mBackKeyPressedTimes = 0;

    @Override
    public void onBackPressed() {

        if (mBackKeyPressedTimes == 0) {
            Toast.makeText(this, "再按一次退出程序 ", Toast.LENGTH_SHORT).show();
            mBackKeyPressedTimes = 1;
            new Thread() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        mBackKeyPressedTimes = 0;
                    }
                }
            }.start();
            return;
        } else {
            ActivitysManager.getManager().exit();
        }
    }

    private Project project;


    private void loadCompanyAndProject() {
        Map<String, Object> map = new HashMap<>();
        map.put("action", "TBSJ");
        map.put("WYGSLX", 2);//（1思源2赛帆）
        map.put("XMLX", 2);
        HttpUtil.check(this, map, new ICallBack() {
            @Override
            public void err(String e) {

            }

            @Override
            public void ok(ResponseBean responseBean) {
                if (responseBean.ok) {
                    List<Company> list = JsonUtil.getList(responseBean.content, Company.class);
                    boolean hasPro = false;
                    for (Company company : list) {
                        if (company.getProject() != null || company.getProject().size() > 0) {
                            for (Project project1 : company.getProject()) {
                                if (project1.getID() == project.getID()) {
                                    hasPro = true;
                                    project.setP_JSSJ(project1.getP_JSSJ());
                                    break;
                                }
                            }
                        }
                    }
                    if (hasPro) {
                        checkPro(project);
                    } else {
                        goSeverSet();
                    }


                } else {
                    goSeverSet();
                }

            }

        });
    }

    private void goSeverSet() {
        showDialog("项目未授权！请选择已授权项目", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(ServerSetActivity.class);
                        ActivitysManager.getManager().removeActivity(MainActivity.this);
                    }
                }
        );
    }

    private void checkPro(Project project) {
        boolean isTest = project.getP_SFQY() != 0;
        if (isTest) {
            String csTime = project.getP_JSSJ();
            if (TextUtils.isEmpty(csTime)) {
                showDialog("试用时间已过期！请选择已授权项目", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(ServerSetActivity.class);
                        ActivitysManager.getManager().removeActivity(MainActivity.this);
                    }
                } );

                 return;
            }
            Date date = StringUtil.getYYYYMMDD(csTime);

            if (date != null) {
                if (date.before(new Date())) {
                    showDialog("试用时间已过期！请选择已授权项目", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            startActivity(ServerSetActivity.class);
                            ActivitysManager.getManager().removeActivity(MainActivity.this);
                        }
                    } );
                    return;

                }


            } else {
                showDialog("试用时间已过期！请选择已授权项目", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        startActivity(ServerSetActivity.class);
                        ActivitysManager.getManager().removeActivity(MainActivity.this);
                    }
                });
                return;
            }
        }


    }


}
